package com.ruoyi.generator.util;
import com.ruoyi.common.utils.file.FileUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.io.*;

public class UnZipFileUtils {


        /**
         * 解压到指定目录
         * @param zipPath
         * @param descDir
         */
        public static void unZipFiles(String zipPath, String descDir) throws IOException {
            unZipFiles(new File(zipPath), descDir);
        }

        /**
         * 解压文件到指定目录
         * 解压后的文件名，和之前一致
         * @param zipFile   待解压的zip文件
         * @param descDir   指定目录
         */
        @SuppressWarnings("rawtypes")
        public static void unZipFiles(File zipFile, String descDir) throws IOException {

            ZipFile zip = new ZipFile(zipFile,Charset.forName("GBK"));//解决中文文件夹乱码
            String name = zip.getName().substring(zip.getName().lastIndexOf('\\')+1, zip.getName().lastIndexOf('.'));

            File pathFile = new File(descDir+name);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }

            for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String zipEntryName = entry.getName();
                InputStream in = zip.getInputStream(entry);
                String outPath = (descDir + name +"/"+ zipEntryName).replaceAll("\\*", "/");

// 判断路径是否存在,不存在则创建文件路径
                File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
                if (!file.exists()) {
                    file.mkdirs();
                }
// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
                if (new File(outPath).isDirectory()) {
                    continue;
                }
// 输出文件路径信息
//          System.out.println(outPath);

                FileOutputStream out = new FileOutputStream(outPath);
                byte[] buf1 = new byte[1024];
                int len;
                while ((len = in.read(buf1)) > 0) {
                    out.write(buf1, 0, len);
                }
                in.close();
                out.close();
            }
            System.out.println("******************解压完毕********************");
            return;

        }
    @Value("${spring.datasource.url}")
    private  String url;
    @Value("${spring.datasource.username}")
    private  String username;
    @Value("${spring.datasource.password}")
    private  String password;
        //测试
        public static void main(String[] args) throws IOException {
            //读取配置文件
            try (BufferedReader br = new BufferedReader(new FileReader("doc/configurations.txt"))) {
                String line1 = br.readLine();
                 br.close();
                unZipFiles(line1,"code/");
                //删除压缩文件
            } catch (IOException e) {
                System.err.println("读取删除文件错误Error reading file: " + e);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            try (BufferedReader br = new BufferedReader(new FileReader("doc/configurations.txt"))) {
              String  line1 = br.readLine();
                FileUtils.deleteFile(line1);
                //删除压缩文件
            } catch (IOException e) {
                System.err.println("读取删除文件错误Error reading file: " + e);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }



        }
    public    Connection getConnection() {

        Connection conn = null;
        try {
            // 建立连接
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
    public  boolean  run(String sqlFilePath) throws Exception {
        try {
            // 建立连接
            Connection conn = this.getConnection();
            // 创建ScriptRunner，用于执行SQL脚本
            ScriptRunner runner = new ScriptRunner(conn);
            runner.setErrorLogWriter(null);
            runner.setLogWriter(null);
            // 遇到错误回滚
            runner.setStopOnError(true);
            Resources.setCharset(Charset.forName("UTF-8"));
            // 执行SQL脚本
            runner.runScript(new InputStreamReader(new FileInputStream(sqlFilePath), "UTF-8"));
            // 关闭连接
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("sql执行失败", e);
        }
        return true;
    }



}
